using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinApp.Models;
using WinApp.Services;

namespace WinApp.Pages
{
    public partial class DialogActionGroupItems : UIEditForm
    {
        private ActionGroup _actionGroup;
        private int _currentGroup = 1;
        private List<ActionGroupItem> _actionGroupItemsGroup1;
        private List<ActionGroupItem> _actionGroupItemsGroup0;
        private PageActionGroups _pageActionGroups = null;
        public PageActionGroups PageActionGroups
        {
            set => _pageActionGroups = value;
        }
        public DialogActionGroupItems(ActionGroup actionGroup)
        {
            _actionGroup = actionGroup;
            InitializeComponent();
            BindGroupType();
            BindActionTypeComboBox();

            dgvActions.AutoGenerateColumns = false;
            pnlBtm.Visible = false;

            LoadData();
        }


        private void DialogActionGroupItems_Load(object sender, EventArgs e)
        {
            cmbActionType.SelectedIndex = 0;
        }

        private void LoadData()
        {
            _actionGroupItemsGroup1 = DataHelper.GetActionGroupItemsByGroup(_actionGroup.Id, 1);
            btnGroup1.TipsText = _actionGroupItemsGroup1.Count.ToString();
            _actionGroupItemsGroup0 = DataHelper.GetActionGroupItemsByGroup(_actionGroup.Id, 0);
            btnGroup0.TipsText = _actionGroupItemsGroup0.Count.ToString();
            if (_currentGroup == 1)
            {
                dgvActions.DataSource = _actionGroupItemsGroup1;
                iudSequence.Maximum = _actionGroupItemsGroup1.Count + 1;
                iudSequence.Value = _actionGroupItemsGroup1.Count + 1;
            }
            else
            {
                dgvActions.DataSource = _actionGroupItemsGroup0;
                iudSequence.Maximum = _actionGroupItemsGroup0.Count + 1;
                iudSequence.Value = _actionGroupItemsGroup0.Count + 1;
            }            
        }

        private void BindGroupType()
        {
            List<GroupTypeComboBoxItem> list = new List<GroupTypeComboBoxItem>
            {
                new GroupTypeComboBoxItem { DisplayText = "顺序", Value = ActionGroupType.Sequential },
                new GroupTypeComboBoxItem { DisplayText = "分支", Value = ActionGroupType.Branch },
                new GroupTypeComboBoxItem { DisplayText = "循环", Value = ActionGroupType.Loop },
                new GroupTypeComboBoxItem { DisplayText = "定次", Value = ActionGroupType.FixedCount }
            };
            cmbActionGroupType.DataSource = list;
            cmbActionGroupType.DisplayMember = "DisplayText";
            cmbActionGroupType.ValueMember = "Value";

            txtActionGroupName.Text = _actionGroup.Name;
            cmbActionGroupType.SelectedValue = _actionGroup.GroupType;
            txtPcp.Text = GetGroupPcpText(_actionGroup);

            if (_actionGroup.GroupType != ActionGroupType.Branch)
            {
                btnGroup0.Visible = false;
            }
        }


        private void BindActionTypeComboBox()
        {
            List<ActionTypeComboBoxItem> list = new List<ActionTypeComboBoxItem>()
            {
                new ActionTypeComboBoxItem { DisplayText = "点击动作", Value = ActionType.ActionClick },
                new ActionTypeComboBoxItem { DisplayText = "OCR识别", Value = ActionType.ActionOcr },
                new ActionTypeComboBoxItem { DisplayText = "头像匹配", Value = ActionType.ActionImageMatch },
                new ActionTypeComboBoxItem { DisplayText = "动作群组", Value = ActionType.ActionGroup },
                new ActionTypeComboBoxItem { DisplayText = "延迟", Value = ActionType.ActionDelay }
            };
            cmbActionType.DataSource = list;
            cmbActionType.DisplayMember = "DisplayText";
            cmbActionType.ValueMember = "Value";


            cmbAction.DisplayMember = "Name";
            cmbAction.ValueMember = "Id";
        }

        private string GetGroupPcpText(ActionGroup g)
        {
            switch (g.GroupType)
            {
                case ActionGroupType.Sequential:
                    return string.Empty;
                case ActionGroupType.Branch:
                case ActionGroupType.Loop:
                    string c = string.Empty;
                    switch (g.Condition)
                    {
                        case ConditionType.LessThan:
                            c = "<";
                            break;
                        case ConditionType.LessThanOrEqual:
                            c = "<=";
                            break;
                        case ConditionType.GreaterThan:
                            c = ">";
                            break;
                        case ConditionType.GreaterThanOrEqual:
                            c = ">=";
                            break;
                        case ConditionType.Equal:
                            c = "=";
                            break;
                        case ConditionType.NotEqual:
                            c = "!=";
                            break;
                        case ConditionType.Contains:
                            c = "⊆";
                            break;
                        case ConditionType.NotContains:
                            c = "⊈";
                            break;
                        default:
                            c = string.Empty;
                            break;
                    }
                    string p1v = string.Empty;
                    switch (g.Param1Type)
                    {
                        case ParameterType.Ocr:
                            var ocrAction = DataHelper.GetActionOcrById(int.Parse(g.Param1Value));
                            p1v = ocrAction.Name;
                            break;
                        case ParameterType.Match:
                            var matchAction = DataHelper.GetActionImageMatchById(int.Parse(g.Param1Value));
                            p1v = matchAction.Name;
                            break;
                        default:
                            p1v = g.Param1Value;
                            break;
                    }
                    string p2v = string.Empty;
                    switch (g.Param2Type)
                    {
                        case ParameterType.Ocr:
                            var ocrAction = DataHelper.GetActionOcrById(int.Parse(g.Param2Value));
                            p2v = ocrAction.Name;
                            break;
                        case ParameterType.Match:
                            var matchAction = DataHelper.GetActionImageMatchById(int.Parse(g.Param2Value));
                            p2v = matchAction.Name;
                            break;
                        default:
                            p2v = g.Param2Value;
                            break;
                    }
                    return $"{p1v}{c}{p2v}";
                case ActionGroupType.FixedCount:
                    return $"{g.Param1Value}次";
                default:
                    return string.Empty;
            }
        }

        private void btnGroup_Click(object sender, EventArgs e)
        {
            UISymbolButton btn = sender as UISymbolButton;
            _currentGroup = btn.TagString == "1" ? 1 : 0;
            if (_currentGroup == 1)
            {
                btnGroup1.LightStyle = false;
                btnGroup0.LightStyle = true;
            }
            else
            {
                btnGroup0.LightStyle = false;
                btnGroup1.LightStyle = true;
            }
            LoadData();
        }

        private void cmbActionType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbActionType.SelectedItem == null)
                return;
            ActionTypeComboBoxItem item = cmbActionType.SelectedItem as ActionTypeComboBoxItem;
            switch (item.Value)
            {
                case ActionType.ActionGroup:
                    List<ActionGroup> agl = DataHelper.GetActionGroupsExclude(_actionGroup.Id, txtFilter.Text);
                    cmbAction.DataSource = agl;
                    break;
                case ActionType.ActionClick:
                    List<ActionClick> acl = DataHelper.GetActionClicks(txtFilter.Text);
                    cmbAction.DataSource = acl;
                    break;
                case ActionType.ActionOcr:
                    List<ActionOcr> aol = DataHelper.GetActionOcrs(txtFilter.Text);
                    cmbAction.DataSource = aol;
                    break;
                case ActionType.ActionImageMatch:
                    List<ActionImageMatch> ail = DataHelper.GetActionImageMatches(txtFilter.Text);
                    cmbAction.DataSource = ail;
                    break;
                case ActionType.ActionDelay:                    
                    cmbAction.DataSource = DataHelper.GetActionDelays();
                    break;
            }
        }

        private void dgvActions_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgvActions.SelectedRows.Count == 0)
                {
                    iudSequence.Maximum = dgvActions.RowCount + 1;
                    uiTitlePanel1.Text = "新增动作条目";
                    btnSave.Text = "新增";
                    return;
                }

                var selectedItem = dgvActions.SelectedRows[0].DataBoundItem as ActionGroupItem;
                if (selectedItem == null)
                {
                    iudSequence.Maximum = dgvActions.RowCount + 1;
                    uiTitlePanel1.Text = "新增动作条目";
                    btnSave.Text = "新增";
                    return;
                }
                iudSequence.Maximum = dgvActions.RowCount;
                btnSave.Text = "保存";
                uiTitlePanel1.Text = "修改动作条目";

                txtFilter.Clear();
                btnFilterAction.PerformClick();
                // 绑定ActionType
                cmbActionType.SelectedValue = selectedItem.ActionType;

                // 根据ActionType加载对应的Action数据
                switch (selectedItem.ActionType)
                {
                    case ActionType.ActionGroup:
                        var actionGroup = DataHelper.GetActionGroupById(selectedItem.ActionId);
                        cmbAction.SelectedValue = actionGroup?.Id;
                        break;
                    case ActionType.ActionClick:
                        var actionClick = DataHelper.GetActionClickById(selectedItem.ActionId);
                        cmbAction.SelectedValue = actionClick?.Id;
                        break;
                    case ActionType.ActionOcr:
                        var actionOcr = DataHelper.GetActionOcrById(selectedItem.ActionId);
                        cmbAction.SelectedValue = actionOcr?.Id;
                        break;
                    case ActionType.ActionImageMatch:
                        var actionImageMatch = DataHelper.GetActionImageMatchById(selectedItem.ActionId);
                        cmbAction.SelectedValue = actionImageMatch?.Id;
                        break;
                    case ActionType.ActionDelay:
                        var actionDelay = DataHelper.GetActionDelay(selectedItem.ActionId);
                        cmbAction.SelectedValue = actionDelay?.Id;
                        break;
                }

                // 绑定序号
                iudSequence.Value = selectedItem.Sequence;
            }
            catch (Exception ex)
            {
                this.ShowErrorTip("数据绑定失败：" + ex.Message);
                Serilog.Log.Error(ex, "dgvActions_SelectionChanged失败");
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                // 清除选择
                dgvActions.ClearSelection();
                
                // 重置控件状态
                cmbActionType.SelectedIndex = 0;
                cmbAction.SelectedIndex = -1;
                
                // 设置序号为当前最大序号+1
                if (_currentGroup == 1)
                {
                    iudSequence.Value = _actionGroupItemsGroup1.Count + 1;
                }
                else
                {
                    iudSequence.Value = _actionGroupItemsGroup0.Count + 1;
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorTip("清除选择失败：" + ex.Message);
                Serilog.Log.Error(ex, "btnClear_Click失败");
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvActions.SelectedRows.Count == 0)
                {
                    this.ShowWarningTip("请先选择要删除的项");
                    return;
                }

                var selectedItem = dgvActions.SelectedRows[0].DataBoundItem as ActionGroupItem;
                if (selectedItem == null)
                    return;

                if (this.ShowAskDialog("确认删除选中项？"))
                {
                    // 删除数据
                    DataHelper.DeleteActionGroupItem(selectedItem.Id);
                    
                    // 重新加载数据
                    LoadData();
                    if (_pageActionGroups != null)
                        _pageActionGroups.RefreshActionGroup();

                    // 清除选择
                    btnClear_Click(null, null);
                    
                    this.ShowSuccessTip("删除成功");
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorTip("删除失败：" + ex.Message);
                Serilog.Log.Error(ex, "btnDelete_Click失败");
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前选中的Action
                if (cmbAction.SelectedItem == null)
                {
                    this.ShowWarningTip("请选择具体动作");
                    return;
                }

                var actionType = ((ActionTypeComboBoxItem)cmbActionType.SelectedItem).Value;
                var sequence = (int)iudSequence.Value;
                var actionId = 0;

                // 根据不同类型获取ActionId
                switch (actionType)
                {
                    case ActionType.ActionGroup:
                        actionId = ((ActionGroup)cmbAction.SelectedItem).Id;
                        break;
                    case ActionType.ActionClick:
                        actionId = ((ActionClick)cmbAction.SelectedItem).Id;
                        break;
                    case ActionType.ActionOcr:
                        actionId = ((ActionOcr)cmbAction.SelectedItem).Id;
                        break;
                    case ActionType.ActionImageMatch:
                        actionId = ((ActionImageMatch)cmbAction.SelectedItem).Id;
                        break;
                    case ActionType.ActionDelay:
                        actionId = ((ActionDelay)cmbAction.SelectedItem).Id;
                        break;
                }

                var currentItems = _currentGroup == 1 ? _actionGroupItemsGroup1 : _actionGroupItemsGroup0;

                if (dgvActions.SelectedRows.Count == 0) // 新增模式
                {                    
                    // 新增数据
                    var newItem = new ActionGroupItem
                    {
                        ActionGroupId = _actionGroup.Id,
                        ActionType = actionType,
                        ActionId = actionId,
                        Sequence = sequence,
                        Group = _currentGroup
                    };
                    DataHelper.InsertActionGroupItem(newItem);
                }
                else // 修改模式
                {
                    var selectedItem = dgvActions.SelectedRows[0].DataBoundItem as ActionGroupItem;
                    if (selectedItem == null) return;
                    
                    // 更新选中项
                    selectedItem.ActionType = actionType;
                    selectedItem.ActionId = actionId;
                    selectedItem.Sequence = sequence;
                    DataHelper.UpdateActionGroupItem(selectedItem);
                }

                // 重新加载数据
                LoadData();
                if (_pageActionGroups != null)
                    _pageActionGroups.RefreshActionGroup();

                // 清除选择
                btnClear_Click(null, null);

                this.ShowSuccessTip("保存成功");
            }
            catch (Exception ex)
            {
                this.ShowErrorTip("保存失败：" + ex.Message);
                Serilog.Log.Error(ex, "btnSave_Click失败");
            }
        }
    }

    public class ActionTypeComboBoxItem
    {
        public string DisplayText { get; set; } // 显示的文本
        public ActionType Value { get; set; }          // 对应的值

        public override string ToString()
        {
            return DisplayText; // 用于在 UIComboBox 中显示
        }
    }
}
